<template>
	<view class="kitchen-container">
		<!-- 顶部情侣厨房插画 -->
		<view class="header-illustration">
			<image src="../../static/couple_photo.jpg" mode="aspectFit"></image>
			<text class="slogan">为亲爱的TA准备爱的味道</text>
		</view>

		<!-- 爱心进度条 -->
		<view class="love-progress">
			<text class="progress-text">本月甜蜜指数</text>
			<view class="progress-bar">
				<view class="inner-bar" :style="{ width: progress + '%' }">
					<text class="progress-count">{{ cookedCount }}份心意</text>
				</view>
			</view>
		</view>

		<!-- 上传菜品按钮 -->
		<view class="floating-button" @click="showUpload = true">
			<u-icon name="plus-circle" size="60" color="#FF69B4"></u-icon>
			<text class="button-tip">为TA添加新美味</text>
		</view>

		<!-- 浪漫上传弹窗 -->
		<u-popup :show="showUpload" @close="showUpload = false" mode="bottom" border-radius="40" closeable>
			<view class="love-upload">
				<view class="heart-border">
					<text class="upload-title">❤ 添加爱的料理 ❤</text>
					<u-form :model="dishForm" ref="dishForm">
						<!-- 菜品名称 -->
						<u-form-item label="爱的名称" prop="name" :border-bottom="false">
							<u-input v-model="dishForm.name" placeholder="给这道菜起个甜蜜的名字" shape="circle">
								<template #prefix>
									<u-icon name="heart" color="#FF69B4"></u-icon>
								</template>
							</u-input>
						</u-form-item>

						<!-- 修改后的菜品分类选择器 -->
						<u-form-item label="情感分类" prop="category">
							<u-input v-model="selectedCategoryLabel" placeholder="请选择爱的分类" shape="circle"
								@focus="showCategoryPicker = true">
								<template #prefix>
									<u-icon name="heart" color="#FF69B4"></u-icon>
								</template>
								<template #suffix>
									<u-icon name="arrow-down"
										:class="['arrow-icon', { 'rotate': showCategoryPicker }]"></u-icon>
								</template>
							</u-input>
						</u-form-item>

						<!-- 价格输入 -->
						<u-form-item label="爱的定价" prop="price">
							<u-input v-model="dishForm.price" type="number" placeholder="为TA定个暖心价格" shape="circle">
								<template #prefix>
									<u-icon name="heart" color="#FF69B4"></u-icon>
								</template>
								<template #suffix>
									<text class="price-suffix">元</text>
								</template>
							</u-input>
						</u-form-item>

						<!-- 图片上传 -->
						<u-form-item label="美味瞬间" prop="image">
							<view class="love-uploader">
								<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
									multiple :maxCount="10">
								</u-upload>
							</view>
						</u-form-item>

						<!-- 提交按钮 -->
						<u-button @click="submitDish" shape="circle" :customStyle="submitStyle">
							<text>❤ 提交爱的食谱 ❤</text>
						</u-button>
					</u-form>
				</view>
			</view>
		</u-popup>

		<!-- 菜品管理 -->
		<scroll-view scroll-y class="dish-management">
			<view class="category-section" v-for="cat in categories" :key="cat.value">
				<view class="category-header">
					<u-icon :name="cat.icon" color="#FF69B4"></u-icon>
					<text class="category-title">{{ cat.name }}</text>
					<text class="dish-count">{{ getDishCount(cat.value) }}道心意</text>
				</view>

				<!-- <view class="dish-list">
					<view v-for="dish in getDishes(cat.value)" :key="dish.id" class="dish-card">
						<image :src="dish.image" class="dish-image"></image>
						<view class="dish-info">
							<text class="dish-name">{{ dish.name }}</text>
							<text class="dish-price">❤ ￥{{ dish.price }}</text>
							<view class="action-buttons">
								<u-button size="mini" shape="circle" @click="editDish(dish)"
									customStyle="background: #FFF0F5; color: #FF69B4;">
									编辑
								</u-button>
								<u-button size="mini" shape="circle" @click="deleteDish(dish.id)"
									customStyle="background: #FFF0F5; color: #FF69B4;">
									下架
								</u-button>
							</view>
						</view>
					</view>
				</view> -->
			</view>
		</scroll-view>

		<!-- 动态爱心 -->
		<view class="floating-hearts">
			<view v-for="n in 3" :key="n" class="heart" :style="getHeartStyle(n)">❤️</view>
		</view>

		<!-- 底部弹出选择框 -->
		<u-picker :show="showCategoryPicker" :columns="[categories]" keyName="name" closeOnClickOverlay
			@cancel="showCategoryPicker = false" @confirm="handleCategoryConfirm" :showToolbar="true" title="选择情感分类"
			cancelText="取消" confirmText="❤ 确认选择 ❤" cancelColor="#FFB6C1" confirmColor="#FF69B4">
			<template #default="{ item }">
				<view class="picker-item">
					<text class="item-text">{{ item.name }}</text>
				</view>
			</template>
		</u-picker>
	</view>
</template>

<script>
import { addMenuData, getMenuData, addUserMenuData } from "@/api/menus/menus.js"
import fileUploadPublic from '../../api/upload/upload.js';
export default {
	data() {
		return {
			fileList1: [],
			showCategoryPicker: false,
			selectedCategoryLabel: '',
			showUpload: false,
			cookedCount: 0,
			progress: 60,
			categories: [
				{ value: 'hot', label: '热恋推荐' },
				{ value: 'soup', label: '暖心汤类' },
				{ value: 'meat', label: '宠溺荤菜' },
				{ value: 'vegetable', label: '清新素菜' },
				{ value: 'staple', label: '甜蜜主食' },
				{ value: 'drink', label: '心动饮品' }
			],
			dishesData: [],
			dishForm: {
				userId: uni.getStorageSync('userId'),
				name: '',
				menuId: '',
				price: '',
				description: '',
				picture: ''
			},
			submitStyle: {
				background: 'linear-gradient(135deg, #FF9AA2 0%, #FFB7B2 100%)',
				color: '#FFFFFF',
				height: '80rpx'
			}
		}
	},
	computed: {
		categoryOptions() {
			return this.categories.map(item => ({
				...item,
				// 添加额外字段供picker显示
				extra: item.icon
			}))
		}
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: "uploading",
					message: "上传中",
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: "success",
						message: "",
						url: result,
					})
				);
				fileListLen++;
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let name = uni.uploadFile({
					sslVerify: false,
					url: fileUploadPublic, // 仅为示例，非真实的接口地址
					filePath: url,
					name: "filename",
					formData: {
						user: "test",
					},
					success: (res) => {
						setTimeout(() => {
							//用正则表达式取到'/'后面的值
							let url = JSON.parse(res.data).url;
							let urlList = url.split('/')
							this.dishForm.picture = urlList[urlList.length - 1]
							resolve(res.data);
						}, 1000);
					},
				});
			});
		},
		handleCategoryConfirm(e) {
			const [selected] = e.value
			this.dishForm.menuId = selected.category
			this.selectedCategoryLabel = selected.name
			this.showCategoryPicker = false
		},
		// 动态爱心样式
		getHeartStyle(n) {
			return {
				animationDelay: `${n * 0.5}s`,
				left: `${Math.random() * 90 + 5}%`,
				fontSize: `${Math.random() * 20 + 28}rpx`
			}
		},

		// 获取分类菜品数量
		getDishCount(categoryId) {
			const category = this.dishesData.find(c => c.id === categoryId)
			return category ? category.dishes.length : 0
		},

		// 获取分类菜品
		async getDishes() {
			const res = await getMenuData(uni.getStorageSync('userId'))
			this.categories = res.data
		},

		// 编辑菜品
		editDish(dish) {
			this.dishForm = { ...dish }
			this.showUpload = true
		},

		// 删除菜品
		async deleteDish(dishId) {
			try {
				// await this.$api.deleteDish(dishId)
				this.dishesData = this.dishesData.map(cat => {
					cat.dishes = cat.dishes.filter(d => d.id !== dishId)
					return cat
				})
				uni.showToast({ title: '已下架该菜品', icon: 'success' })
			} catch (e) {
				uni.showToast({ title: '操作失败', icon: 'none' })
			}
		},
		// 表单验证
		async validateForm() {
			const rules = {
				name: [{ required: true, message: '给这道菜起个甜蜜的名字吧' }],
				category: [{ required: true, message: '请选择爱的分类' }],
				price: [
					{ required: true, message: '请为TA定个暖心价格' },
					{ type: 'number', message: '价格要填数字哦' },
					{ validator: (v) => v > 0, message: '价格不能为负数' }
				],
				image: [{ required: true, message: '记录下美味瞬间吧' }]
			}

			try {
				await this.$refs.dishForm.validate(rules)
				return true
			} catch (e) {
				return false
			}
		},

		// 提交菜品
		async submitDish() {
			if (!await this.validateForm()) return
			uni.showLoading({ title: '正在保存...' })
			try {
				let res = await addUserMenuData(this.dishForm)
				this.showUpload = false
				this.$refs.dishForm.resetFields()
				this.dishForm.menuId = ''
				this.selectedCategoryLabel = ''
				this.fileList1 = []
				// this.cookedCount++
				uni.showToast({ title: '添加成功！', icon: 'success' })
			} catch (e) {
				uni.showToast({ title: '提交失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		},

		// 初始化数据
		async loadData() {
			try {
				// const res = await this.$api.getDishes()
				// this.dishesData = res.data
			} catch (e) {
				console.error('数据加载失败', e)
			}
		}
	},
	mounted() {
		this.loadData()
		this.getDishes()
	}
}
</script>

<style lang="scss" scoped>
// 选择器箭头动画
.arrow-icon {
	transition: transform 0.3s;

	&.rotate {
		transform: rotate(180deg);
	}
}

// 自定义选择项样式
.picker-item {
	@include flex(row);
	align-items: center;
	padding: 28rpx 32rpx;
	background: #FFF8F8;
	margin: 10rpx 20rpx;
	border-radius: 16rpx;
	transition: all 0.3s;

	&:active {
		background: #FFE6E6;
	}

	.item-text {
		color: #FF69B4;
		font-size: 32rpx;
		font-weight: 500;
	}
}

// 修改picker工具栏样式
::v-deep .u-picker__toolbar {
	background: #FFF0F5 !important;
	border-bottom: 2rpx solid #FFE6E6 !important;

	&__title {
		color: #FF69B4 !important;
		font-weight: bold !important;
	}
}

/* 核心布局样式 */
.kitchen-container {
	height: 100vh;
	background: linear-gradient(135deg, #FFF0F5 0%, #FFE4E1 100%);
	overflow: hidden;
	position: relative;
}

/* 顶部插画 */
.header-illustration {
	position: relative;
	height: 400rpx;

	image {
		width: 100%;
		height: 100%;
	}

	.slogan {
		position: absolute;
		bottom: 40rpx;
		width: 100%;
		text-align: center;
		color: #FFFFFF;
		font-size: 36rpx;
		text-shadow: 0 4rpx 8rpx rgba(255, 105, 180, 0.5);
		font-weight: 500;
	}
}

/* 进度条 */
.love-progress {
	padding: 30rpx 40rpx;

	.progress-text {
		color: #FF69B4;
		font-size: 32rpx;
		display: block;
		margin-bottom: 20rpx;
	}

	.progress-bar {
		height: 40rpx;
		background: #FFE6E6;
		border-radius: 20rpx;
		overflow: hidden;
		position: relative;

		.inner-bar {
			height: 100%;
			background: linear-gradient(90deg, #FF9AA2, #FFB7B2);
			transition: width 0.5s ease;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding: 0 20rpx;

			.progress-count {
				color: white;
				font-size: 24rpx;
				letter-spacing: 2rpx;
			}
		}
	}
}

/* 上传表单 */
.love-upload {
	padding: 40rpx;
	background: #fff;

	.heart-border {
		border: 4rpx dashed #FFB6C1;
		border-radius: 40rpx;
		padding: 40rpx 30rpx;
		background: rgba(255, 255, 255, 0.95);
	}

	.upload-title {
		font-size: 36rpx;
		color: #FF69B4;
		text-align: center;
		margin-bottom: 40rpx;
		display: block;
	}

	.love-uploader {
		height: 300rpx;
		background: #FFF8F8;
		border-radius: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;

		.preview-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.uploader-placeholder {
			width: 340rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			// justify-content: center;
			color: #FFB6C1;

			text {
				display: block;
				margin-top: 20rpx;
				font-size: 28rpx;
			}
		}
	}
}

/* 菜品分类 */
.category-section {
	margin: 30rpx 20rpx;

	.category-header {
		display: flex;
		align-items: center;
		padding: 25rpx 30rpx;
		background: rgba(255, 235, 238, 0.8);
		border-radius: 16rpx;
		margin-bottom: 20rpx;

		.category-title {
			font-size: 32rpx;
			color: #FF69B4;
			margin-left: 20rpx;
		}

		.dish-count {
			margin-left: auto;
			color: #666;
			font-size: 26rpx;
		}
	}
}

/* 菜品卡片 */
.dish-card {
	display: flex;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 30rpx;
	margin: 20rpx 0;
	padding: 25rpx;
	box-shadow: 0 8rpx 24rpx rgba(255, 105, 180, 0.1);

	.dish-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 20rpx;
		flex-shrink: 0;
		background: #f5f5f5;
	}

	.dish-info {
		flex: 1;
		margin-left: 25rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.dish-name {
			font-size: 32rpx;
			color: #FF69B4;
			font-weight: 500;
		}

		.dish-price {
			color: #FF6B6B;
			font-size: 36rpx;
			margin: 15rpx 0;
		}
	}
}

/* 操作按钮 */
.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: auto;

	button {
		flex: 1;
		height: 60rpx !important;
		line-height: 60rpx !important;
	}
}

/* 悬浮按钮 */
.floating-button {
	position: fixed;
	bottom: 80rpx;
	right: 40rpx;
	z-index: 1000;
	display: flex;
	flex-direction: column;
	align-items: center;

	.button-tip {
		color: #FF69B4;
		font-size: 24rpx;
		margin-top: 10rpx;
		text-shadow: 0 2rpx 4rpx rgba(255, 105, 180, 0.2);
	}
}

/* 动态爱心 */
.floating-hearts {
	pointer-events: none;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;

	.heart {
		position: absolute;
		font-size: 40rpx;
		opacity: 0;
		animation: heartFloat 3s infinite linear;
	}
}

@keyframes heartFloat {
	0% {
		opacity: 0;
		transform: translateY(0) scale(1);
	}

	20% {
		opacity: 1;
	}

	100% {
		opacity: 0;
		transform: translateY(-1000rpx) scale(0.5);
	}
}

/* 表单细节调整 */
::v-deep {
	.u-form-item__body__left__content__label {
		color: #FF69B4 !important;
		font-size: 30rpx !important;
	}

	.u-input {
		background: #FFF8F8 !important;
		border-color: #FFB6C1 !important;
		border-radius: 50rpx !important;
		padding: 0 25rpx !important;
	}

	.u-input__input {
		color: #FF6B6B !important;
	}

	.u-upload__wrap {
		padding: 0 !important;
	}
}
</style>